package com.chuan.thinkingjava.thread;


import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.chuan.thinkingjava.db.DBUtil;

/**
 * 120 入库结束，耗时：0 days 0 hours 2 minutes 52 seconds 
 * 50  
 * @author Bowen
 *
 */
public class Import {
	
	static long start = System.currentTimeMillis();
	
	static int count = 1000 * 10000; //查库的条数
	
    public static void main(String[] args) throws SQLException {
    	System.out.println("开始入库");
    	ExecutorService threadPool = Executors.newFixedThreadPool(50);
    	StringBuffer sb_sql = new StringBuffer("insert into user (name,age,sex,content) values");
    	for (int i = 1; i <= count; i++) {
    		if (i % 5000 == 0) { //一次性插入1000条数据
    			String sql = sb_sql.append("('name"+i+"','"+i+"','男','hhhhaahhahah'),").toString().substring(0, sb_sql.length()-1);
    			threadPool.execute(new ImportTask(sql, i));
    			sb_sql = new StringBuffer("insert into user (name,age,sex,content) values");
			} else {
				sb_sql.append("('name"+i+"','"+i+"','男','hhhhaahhahah'),");
			}
		}
    }
    
    public static String formatDuring(long mss) {
		long days = mss / (1000 * 60 * 60 * 24);
		long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
		long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
		long seconds = (mss % (1000 * 60)) / 1000;
		return days + " days " + hours + " hours " + minutes + " minutes "
				+ seconds + " seconds ";
	}
}

class ImportTask implements Runnable {
	
	private String sql;
	
	private int _index;
	
	public ImportTask(String sql,int index) {
		this.sql = sql;
		this._index = index;
	}
	
	@Override
	public void run() {
		
		try {
			DBUtil.insert(sql);
			if (_index == Import.count) {
				System.out.println("入库结束，共插入" + _index +"条数据，耗时：" + Import.formatDuring(System.currentTimeMillis() - Import.start));
			}
		} catch (Exception e) {
		}
		
	}
}
